import os
import logging
import json
import time
from datetime import datetime
from logging.handlers import TimedRotatingFileHandler
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_START_TIMESTAMP = int(time.time())
PROJECT_NAME = "xcnvs_admin"
# PROJECT_VERSION = "1.2" # 2025/1/5
PROJECT_VERSION = "1.3" # 2025/04/01

class Settings(object):
    def __init__(self, filepath):
        self.__filepath = filepath

        settings_data = None
        for encoding in ["utf-8", "gbk"]:
            try:
                f = open(filepath, 'r', encoding=encoding)
                content = f.read()
                settings_data = json.loads(content)
                f.close()
                break
            except Exception as e:
                print("Settings.__init__() error:%s,encoding=%s|%s" % (str(e), encoding, str(filepath)))

        if settings_data:
            self.__settings_data = settings_data
            self.__settings_data_str = str(settings_data)
            self.ip = settings_data.get("ip")
            self.debug = bool(settings_data.get("debug",False))
            self.logDebug = bool(settings_data.get("logDebug",False))
            self.dev = bool(settings_data.get("dev",False))
            self.logDay = int(settings_data.get("logDay",7))
            self.appKey = str(settings_data.get("appKey","xcnvs"))
            self.appSecret = str(settings_data.get("appSecret","xcnvs"))

            self.adminPort = int(settings_data.get("adminPort",9824)) # 服务器端口
            self.adminCacheDuration = int(settings_data.get("adminCacheDuration",300)) # 缓存时长
            self.adminCacheCheckInterval = int(settings_data.get("adminCacheCheckInterval",10)) # 检测缓存周期间隔（单位秒）

            self.fsPort = int(settings_data.get("fsPort",9825))# fs服务器端口
            self.fsMaxBufferSize = int(settings_data.get("fsMaxBufferSize")) # fs服务器运行上传文件最大字节数
            self.fsStorageRecordDuration = int(settings_data.get("fsStorageRecordDuration")) # fs缓存录像片段时长
            self.fsStorageCheckInterval = int(settings_data.get("fsStorageCheckInterval")) # fs检测录像周期间隔（单位秒）
            self.fsProcessNum = int(settings_data.get("fsProcessNum"))
            self.fsStorageDir = str(settings_data.get("fsStorageDir"))

            if not os.path.exists(self.fsStorageDir):
                os.makedirs(self.fsStorageDir)

            self.fsHttpHost = "http://%s:%d" % (self.ip, self.fsPort)

            # 流媒体相关参数
            self.mediaRtspPort = int(settings_data.get("mediaRtspPort"))
            self.mediaHttpPort = int(settings_data.get("mediaHttpPort"))
            self.mediaSecret = str(settings_data.get("mediaSecret"))
            self.mediaStorageDir = str(settings_data.get("mediaStorageDir"))
            self.mediaDstSchema = str(settings_data.get("mediaDstSchema"))
            self.mediaDstApp = str(settings_data.get("mediaDstApp"))
            self.mediaDstRtspHost = "rtsp://%s:%d"%(self.ip, self.mediaRtspPort)
            self.mediaHttpHost = "http://127.0.0.1:%d"%self.mediaHttpPort # 内部调用zlm的接口
        else:
            msg = "read Settings %s error" % str(filepath)
            raise Exception(msg)

    def __del__(self):
        pass

    def getStr(self):
        return self.__settings_data_str

# __log_dir = os.path.join(BASE_DIR, 'log')
__log_dir = "log"
if not os.path.exists(__log_dir):
    os.makedirs(__log_dir)

# __filepath = os.path.join(BASE_DIR, "settings.json")
__filepath = "settings.json"

g_settings = Settings(filepath=__filepath)

def CreateLogger(logDir, is_show_console=False):
    if not os.path.exists(logDir):
        os.makedirs(logDir)

    LOGGER_TIMEFMT = PROJECT_NAME+"%Y%m%d-%H%M%S"
    LOGGER_WHEN = 'd'
    LOGFILE_BACKUPCOUNT = g_settings.logDay

    fileName = os.path.join(logDir, "%s.log" % (datetime.now().strftime(LOGGER_TIMEFMT)))
    if g_settings.logDebug:
        level = logging.DEBUG
    else:
        level = logging.INFO
    logger = logging.getLogger()
    logger.setLevel(level)
    formatter = logging.Formatter('%(asctime)s %(name)s %(lineno)s %(levelname)s %(message)s')

    # 最基础
    # fileHandler = logging.FileHandler(fileName, encoding='utf-8')  # 指定utf-8格式编码，避免输出的日志文本乱码
    # fileHandler.setLevel(level)
    # fileHandler.setFormatter(formatter)
    # logger.addHandler(fileHandler)

    # 时间滚动切分
    # when:备份的时间单位，backupCount:备份保存的时间长度
    timedRotatingFileHandler = TimedRotatingFileHandler(fileName,
                                                        when=LOGGER_WHEN,
                                                        backupCount=LOGFILE_BACKUPCOUNT,
                                                        encoding='utf-8')

    timedRotatingFileHandler.setLevel(level)
    timedRotatingFileHandler.setFormatter(formatter)
    logger.addHandler(timedRotatingFileHandler)

    # 控制台打印
    if is_show_console:
        streamHandler = logging.StreamHandler()
        streamHandler.setLevel(level)
        streamHandler.setFormatter(formatter)
        logger.addHandler(streamHandler)

    return logger
g_logger = CreateLogger(logDir=__log_dir, is_show_console=True)
g_logger.info("%s v%s" % (PROJECT_NAME,PROJECT_VERSION))
